package com.ciwong.epaper.modules.msg.ui;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.bean.MsgPostBean;
import com.ciwong.epaper.bean.MsgtypeBean;
import com.ciwong.epaper.modules.me.ui.JsonParserUtil;
import com.ciwong.epaper.modules.msg.adapter.MyMessageAdapter;
import com.ciwong.epaper.modules.msg.bean.MessageInfo;
import com.ciwong.epaper.modules.msg.bean.MsgTypeConfig;
import com.ciwong.epaper.modules.msg.dao.MsgDao;
import com.ciwong.epaper.modules.msg.util.MessageJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息 页面
 */
public class MyMessageActivity extends BaseActivity {

	private EApplication mEApplication;

	private ListView list_view_msg;

	private View noMsgView;
	private List<MessageInfo> messageInfo = new ArrayList<MessageInfo>();

	/**
	 * 适配器
	 */
	private MyMessageAdapter myMessageAdapter;
	private boolean isOnResumeGetData  =false ;
	private ImageView message_go_back;

	@Override
	protected int setView() {
		return R.layout.activity_my_message;
	}

	@Override
	protected void findViews() {
		list_view_msg = (ListView) findViewById(R.id.list_view_msg);
		noMsgView = findViewById(R.id.no_msg);
		message_go_back = (ImageView) findViewById(R.id.message_go_back);
	}

	@Override
	protected void initEvent() {

		message_go_back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				finish();
			}
		});

		list_view_msg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				MessageInfo info = (MessageInfo) parent.getItemAtPosition(position);
				if (info != null) {
					UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();
					//点击跳转时更新本地的msgId
					if (userInfoBase != null) {
						long userId = userInfoBase.getUserId();
						if (MsgTypeConfig.MSG_SERVICE == info.getMsgGroup()) {
							ESystem.setSharedInt(EConstants.SHARE_KEY_MSG_TYPE_SERVICE_MSG_GROUP_ID + userId, info.getMsgId());
						} else {
							ESystem.setSharedInt(EConstants.SHARE_KEY_MSG_TYPE_HOMEWORK_MSG_GROUP_ID + userId, info.getMsgId());
						}
					}

				}

				MessageJumpManager.jumpToWorkMsgActivity(MyMessageActivity.this, R.string.go_back, info, RequestCode.HomeWorkFragmentResquestCode.QEQ_FOR_HOME_WORK_MSG);
			}
		});
	}

	@Override
	protected void init() {
		hideTitleBar();
		mEApplication = (EApplication) getApplication();
		//setTitleText(R.string.msg_title);
		myMessageAdapter = new MyMessageAdapter(this, messageInfo);
		list_view_msg.setAdapter(myMessageAdapter);
	}

	@Override
	protected void loadData() {

		getLocalMsgList();

	}

	@Override
	protected void onResume() {
		super.onResume();
		//首次onResume不调用
		if(isOnResumeGetData){
			getNetMsgList();
		}

	}

	/**
	 * 获取本地数据
	 */
	private void getLocalMsgList() {
		//从本地取得数据
		SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_MSG_LIST_NEW, new BaseCallBack() {

			@Override
			public void failed(int errorCode, Object data) {
				getNetMsgList();
			}

			@Override
			public void failed(Object data) {
				getNetMsgList();
			}

			@Override
			public void success(Object data) {
				if (data != null) {
					List<MessageInfo> messageInfos = (List<MessageInfo>) data;
					messageInfos.clear();
					messageInfos.addAll(messageInfos);
					myMessageAdapter.notifyDataSetChanged();
				}
				getNetMsgList();
			}
		});

	}

	//正式网络请求数据接口
	private void getNetMsgList() {
		UserInfoBase userInfoBase = mEApplication.getUserInfoBase();
		if (null != userInfoBase) {
			showMiddleProgressBar(getTitleText());
			MsgPostBean msgPostBean = getMsgPostBean(userInfoBase.getUserId());
			String postJson = JsonParserUtil.toJson(msgPostBean);
			MsgDao.getInstance().getMessageListNew(postJson, new BaseExtCallBack(MyMessageActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

				@Override
				public void failed(int errorCode, Object data) {
					super.failed(errorCode, data);
					CWLog.i(TAG, "【Message】  获取网络消息数目失败");
					hideMiddleProgressBar();
					ToastUtil.INSTANCE.toastCenterError("获取未读消息失败");
					noMsgView.setVisibility(myMessageAdapter.getCount() <= 0 ? View.VISIBLE : View.GONE);
					FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MESSAGE,data == null ? "" : "失败信息：" + data.toString(),"获取未读消息列表失败");
				}

				@Override
				public void failed(Object data) {
					CWLog.i(TAG, "【Message】  获取网络消息数目失败");
					hideMiddleProgressBar();
					ToastUtil.INSTANCE.toastCenterError("获取未读消息失败");
					noMsgView.setVisibility(myMessageAdapter.getCount() <= 0 ? View.VISIBLE : View.GONE);
					FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MESSAGE,data == null ? "" : "失败信息：" + data.toString(),"获取未读消息列表失败");

				}

				public void success(Object data) {
					if (data != null) {
						ArrayList<MessageInfo> infos = (ArrayList<MessageInfo>) data;
						messageInfo.clear();
						messageInfo.addAll(infos);
						myMessageAdapter.notifyDataSetChanged();
						hideMiddleProgressBar();
						noMsgView.setVisibility(myMessageAdapter.getCount() <= 0 ? View.VISIBLE : View.GONE);
						//缓存数据本地数据无网络也可以操作
						SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_MSG_LIST_NEW, infos);
					}

				}
			});
		}

		if(!isOnResumeGetData){
			isOnResumeGetData = true;
		}

	}


	private MsgPostBean getMsgPostBean(long userId) {
		MsgPostBean msgPostBean = new MsgPostBean();
		msgPostBean.setBrandId(EApplication.BRAND_ID);
		msgPostBean.setUserId(userId);

		MsgtypeBean msgtypeListBeanHomework = new MsgtypeBean();
		int homeworkMsgId= ESystem.getSharedInt(EConstants.SHARE_KEY_MSG_TYPE_HOMEWORK_MSG_GROUP_ID + userId, 0);
		msgtypeListBeanHomework.setMsgId(homeworkMsgId);
		msgtypeListBeanHomework.setMsgGroup(MsgTypeConfig.MSG_WORK_NOTIFICATION);

		MsgtypeBean msgtypeListBeanMail = new MsgtypeBean();
		int mainMsgId = ESystem.getSharedInt(EConstants.SHARE_KEY_MSG_TYPE_SERVICE_MSG_GROUP_ID + userId, 0);
		msgtypeListBeanMail.setMsgId(mainMsgId);
		msgtypeListBeanMail.setMsgGroup(MsgTypeConfig.MSG_SERVICE);

		List<MsgtypeBean> msgtypeListBeans = new ArrayList<>();
		msgtypeListBeans.add(msgtypeListBeanHomework);
		msgtypeListBeans.add(msgtypeListBeanMail);
		msgPostBean.setMsgtypeList(msgtypeListBeans);
		return msgPostBean;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		CWLog.i("onActivityResult", requestCode + "");
		if (RESULT_OK == resultCode && requestCode == RequestCode.HomeWorkFragmentResquestCode.QEQ_FOR_HOME_WORK_MSG) {
			sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG));
			finish();
		}
	}
}
